# -*- coding: utf-8 -*-

import datetime
from openerp import models
from openerp.osv import osv, fields, orm
from openerp import tools

class account_invoice(models.Model):
    _inherit = "account.invoice"

    _columns = {
        'create_date': fields.datetime('Creation datetime', readonly=True),
    }

    #小于10秒钟则认为刚刚建立的发票，可以自动记账
    def check_invoice_just_create(self, cr, uid, ids, context=None):
        assert len(ids) == 1, 'This option should only be used for a single id at a time.'
        invoice = self.browse(cr, uid, ids, context=context)[0]
        diff = datetime.datetime.strptime(fields.datetime.now(), '%Y-%m-%d %H:%M:%S') - \
            datetime.datetime.strptime(invoice.create_date, '%Y-%m-%d %H:%M:%S')
        if diff.seconds < 10:
            return True
        else:
            return False

class account_entries_report(osv.osv):
    _inherit = "account.entries.report"

    _columns = {
        'user_id': fields.many2one('res.users', u'销售员', readonly=True),
    }

    def init(self, cr):
        tools.drop_view_if_exists(cr, 'account_entries_report')
        cr.execute("""
            create or replace view account_entries_report as (
            select
                l.id as id,
                am.date as date,
                l.date_maturity as date_maturity,
                l.date_created as date_created,
                am.ref as ref,
                am.state as move_state,
                l.state as move_line_state,
                l.reconcile_id as reconcile_id,
                l.partner_id as partner_id,
                l.product_id as product_id,
                l.product_uom_id as product_uom_id,
                am.company_id as company_id,
                am.journal_id as journal_id,
                p.fiscalyear_id as fiscalyear_id,
                am.period_id as period_id,
                l.account_id as account_id,
                l.analytic_account_id as analytic_account_id,
                a.type as type,
                a.user_type as user_type,
                rp.user_id,
                1 as nbr,
                l.quantity as quantity,
                l.currency_id as currency_id,
                l.amount_currency as amount_currency,
                l.debit as debit,
                l.credit as credit,
                l.debit-l.credit as balance
            from
                account_move_line l
                left join account_account a on (l.account_id = a.id)
                left join account_move am on (am.id=l.move_id)
                left join account_period p on (am.period_id=p.id)
                left join res_partner rp on (rp.id=l.partner_id)
                where l.state != 'draft'
            )
        """)
